#!/bin/sh
# Starts the launcher on Linux (scripts/after-pack.js puts this in front of the Electron binary).
#
# Chromium's sandbox needs either unprivileged user namespaces or a root-owned setuid chrome-sandbox.
# Ubuntu 24.04 and newer block user namespaces for apps without an AppArmor profile, the AppImage's
# mount and the .tar.gz can't carry a setuid file, and Chromium 85 can't start the setuid helper from
# a folder with a space in its name (the .deb installs to "/opt/L.O.S Farms"). In each of those cases
# Electron aborts before any of our code runs, so the choice has to be made here, before it starts.
self=$(readlink -f "$0")
here=$(dirname "$self")
bin="$self.bin"

userns_ok() {
  [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null)" = 1 ] && return 1
  [ "$(cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null)" = 0 ] && return 1
  [ "$(cat /proc/sys/user/max_user_namespaces 2>/dev/null)" = 0 ] && return 1
  if command -v unshare >/dev/null 2>&1; then
    unshare -Ur true >/dev/null 2>&1 || return 1
  fi
  return 0
}

suid_ok() {
  case "$here" in *[[:space:]]*) return 1 ;; esac
  [ -u "$here/chrome-sandbox" ] && [ "$(stat -c %u "$here/chrome-sandbox" 2>/dev/null)" = 0 ]
}

for arg in "$@"; do
  [ "$arg" = --no-sandbox ] && exec "$bin" "$@"
done
if userns_ok || suid_ok; then
  exec "$bin" "$@"
fi
exec "$bin" --no-sandbox "$@"
